package com.ys.controller.api.purchase;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.purchase.TcgPurchaseAppointOrder;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.purchase.TcgPurchaseAppointOrderService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tcgPurchaseAppointOrder")
public class ApiInterTcgPurchaseAppointOrderController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchaseAppointOrderController.class);

	@Autowired
	private CommonApiService<TcgPurchaseAppointOrder> commonApiService;

	@Autowired
	private TcgPurchaseAppointOrderService tcgPurchaseAppointOrderService;

	@RequiresPermissions("tcgPurchaseAppointOrder:view")
	@RequestMapping("/search")
	@ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcgPurchaseAppointOrder cond){
		cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
				.addField("U.UserId + '/' + U.UserName AS _ys_createUserName");//制单人

		cond.addLeftJoin("TB_CompanyInfo B ON B.Vid=A.CompanyVid")
		.addLeftJoin("THR_OperateCompanyApply C ON C.VGsBm =A.Vgsbm")
		.addLeftJoin("TS_UserChange G on G.Id = C.OperatorChangeId")
		.addField("G.UserId operatorUserId")
		.addField("G.UserName operatorUserName")
		.addLeftJoin("TCG_PurchaseAppointOrderItem D ON D.Pbid=A.Bid")
		.addLeftJoin("TCG_PurchaseAppointOrderProductComponent E ON E.Pid=D.id")
		.addField("B.Vname companyName,C.VGsJc vgsjc,C.CUser userId,D.ProductCode productCode," +
				"D.ProductName productName,D.CodeMerge codeMerge,D.ReserveNumber reserveNumber," +
				"E.SubCode subCode,E.SubName subName,E.SubCodeMerge subCodeMerge,E.SubBomNumber subBomNumber," +
				"E.SubBomPrice subBomPrice,E.SubReserveNumber subReserveNumber,E.SubTotalPrice subTotalPrice")
		.addField("CASE WHEN A.StateCancel=1  THEN 2 ELSE A.EffectStock END  effectStock")//流程状态
		.addField("CASE WHEN A.EffectStock = 0 THEN '未生效' WHEN A.EffectStock = 1 THEN '已生效' ELSE '已取消' END effectStock")//
		.setOrderby("A.Bid DESC");
		cond = commonApiService.dataAuth(MenuId.TCG_PurchaseAppointOrder, cond);

		return commonApiService.searchLay(cond);
	}


	/*
	* 去重
	*/
	@RequestMapping("/getProductCode")
	@ResponseBody
	public R getProductCode(@RequestParam("productCode") List<String> idList){
		//去重
		Map<String, List<String>> groupsByCode = idList.stream().collect(Collectors.groupingBy(e->e));
		List<String> codeList = new ArrayList<>();
		//遍历，填入去重的商品编码
		groupsByCode.forEach((k, v) -> {
			codeList.add(k);
		});
		String codes = "";
		for( String productCode:codeList ){
			if(codes == null || codes.equals("")){
				codes = "'"+ productCode + "'";
			}else {
				codes = codes + ",'"+ productCode + "'";
			}
		}
		List<Map<String,Object>> lastDetail= new TpProductActiveComponent()
				.addLeftJoin("TP_ProductActive B ON B.Code =A.Pcode")
				.addField("B.Name productName,B.Code productCode,B.CodeMerge codeMerge")
				.where("B.code IN ( "+ codes+" )")
				.queryMap();
		R r=R.ok();
		r.put("data",lastDetail);
		return r;

	}

	/**
	 * 删除
	 */
	@PostMapping("/deleteTrue")
	@ResponseBody
	public R deleteTrue(HttpServletRequest request, Long id){
		try {
			return tcgPurchaseAppointOrderService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	/*
	 * 导出
	 */
	@RequiresPermissions("tcgPurchaseAppointOrder:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchaseAppointOrder cond) throws Exception{
		cond.setOrderby("A.Id DESC");

		cond.setPage(0).setSize(999999);
		cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
				.addField("U.UserId + '/' + U.UserName AS _ys_createUserName");//制单人

		cond.addLeftJoin("TB_CompanyInfo B ON B.Vid=A.CompanyVid")
				.addLeftJoin("THR_OperateCompanyApply C ON C.VGsBm =A.Vgsbm")
				.addLeftJoin("TS_UserChange G on G.Id = C.OperatorChangeId")
				.addField("G.UserId operatorUserId")
				.addField("G.UserName operatorUserName")
				.addLeftJoin("TCG_PurchaseAppointOrderItem D ON D.Pbid=A.Bid")
				.addLeftJoin("TCG_PurchaseAppointOrderProductComponent E ON E.Pid=D.id")
				.addField("B.Vname companyName,C.VGsJc vgsjc,C.CUser userId,D.ProductCode productCode," +
						"D.ProductName productName,D.CodeMerge codeMerge,D.ReserveNumber reserveNumber," +
						"E.SubCode subCode,E.SubName subName,E.SubCodeMerge subCodeMerge,E.SubBomNumber subBomNumber," +
						"E.SubBomPrice subBomPrice,E.SubReserveNumber subReserveNumber,E.SubTotalPrice subTotalPrice")
				.addField("CASE WHEN A.StateCancel=1  THEN 2 ELSE A.EffectStock END  effectStock")//流程状态
				.addField("CASE WHEN A.EffectStock = 0 THEN '未生效' WHEN A.EffectStock = 1 THEN '已生效' ELSE '已取消' END effectStock")//
				.setOrderby("A.Bid DESC");

		List<Map<String, Object>> listData = cond.queryMap();

    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCG_PurchaseAppointOrder)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();


        ExportExcelUtils<TcgPurchaseAppointOrder> util = new ExportExcelUtils<TcgPurchaseAppointOrder>(new TcgPurchaseAppointOrder());

        String toFilePath = util.exportExcel(listData, listField, "预约采购单");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }
	/**
	 * 编辑
	 */
	@PostMapping("/toEdit")
	@ResponseBody
	public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData){
		try {
			return tcgPurchaseAppointOrderService.edit(params, MenuId.TCG_PurchaseAppointOrder,subData);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	/**
	 * 新增
	 */
	@RequiresPermissions("tcgPurchaseAppointOrder:add")
	@RequestMapping("/toAdd")
	@ResponseBody
	public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData){
		try {
			//新增
			return tcgPurchaseAppointOrderService.add(params,subData);
		} catch (Exception e) {
			logger.error("新增出错：",e.getMessage(),e);
			return R.error(e.getCause().getMessage());
		}
	}

	/**
	 * 流转通过
	 */
	@PostMapping("/flowPass")
	@ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		try {
			return tcgPurchaseAppointOrderService.flowPass(id, ShiroUtils.getUserId());
		} catch (Exception e) {
			logger.error("预约采购审批出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		}
	}

	/**
	 * 流转退回
	 */
	@PostMapping("/flowRefuse")
	@ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		try {
			return tcgPurchaseAppointOrderService.flowRefuse(id, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			logger.error("预约采购审批出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		}
	}



	/**
	 * 流转驳回
	 */
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		try {
			return tcgPurchaseAppointOrderService.flowInit(id, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			logger.error("预约采购审批出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		}
	}

}
